package cn.example.practice.servlet;

import cn.example.practice.db.UserDao;
import cn.example.practice.model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.Optional;

@WebServlet(name = "LoginServlet", urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();

        String uname = request.getParameter("uname");
        String upwd = request.getParameter("pwd");
        String code = request.getParameter("vcode");

        Object code1 = session.getAttribute("code");
        if (null != code1 && code.equals(code1.toString())) {
            UserDao dao = new UserDao();
            User user = new User(uname, upwd);
            Optional<User> loginUser = dao.getUserByCredentials(user);
            if (loginUser.isPresent()) {
                session.setAttribute("loginUser", loginUser.get());
                response.sendRedirect(request.getContextPath() + "/shopListServlet");
            } else {
                request.setAttribute("errMsg", "用户名或密码错误");
                request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
            }
            session.removeAttribute("code");
        } else {
            request.setAttribute("errMsg", "验证码错误");
            request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        }
    }
}
